package com.javajun.service;

import java.util.HashSet;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.javajun.custom.BaseService;
import com.javajun.custom.Success;
import com.javajun.entity.Teacher;
import com.javajun.form.StudentForm;
import com.javajun.form.TeacherForm;
import com.javajun.repository.TeacherRepository;

@Service
public class TeacherService extends BaseService<Teacher, Integer>{

    @Autowired
    private TeacherRepository teacherRepository;
    
    @Autowired
    private SysUserService sysUserService;
    
    @Autowired
    private SysRoleService sysRoleService;
    
    private BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

    /**
     * #安全查询
     * @param form
     * @return
     */
    public Specification<Teacher> buildSpec(TeacherForm form) {
        Specification<Teacher> specification = new Specification<Teacher>() {

            /**
             * 
             */
            private static final long serialVersionUID = 1L;

            @Override
            public Predicate toPredicate(Root<Teacher> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                HashSet<Predicate> rules=new HashSet<>();
                String username = form.getUsername();
                if(StringUtils.hasText(username)) {
                    rules.add(cb.like(root.get("username"), "%"+username+"%"));
                }
                String phone = form.getPhone();
                if(StringUtils.hasText(phone)) {
                    rules.add(cb.like(root.get("phone"), "%"+phone+"%"));
                }
                String name = form.getName();
                if(StringUtils.hasText(name)) {
                    rules.add(cb.like(root.get("name"), "%"+name+"%"));
                }
                return cb.and(rules.toArray(new Predicate[rules.size()]));
            }
        };
        return specification;
    }

    public void save(StudentForm form) {
        Teacher entity = new Teacher();
        Integer id = form.getId();
        if(id != null) {
            entity = findById(id);
        } else {
            entity.setPassword(encoder.encode("1111"));
            entity.getSysRole().add(sysRoleService.getTeacherRole());
        }
        entity.setName(form.getName());
        entity.setEmail(form.getEmail());
        entity.setUsername(form.getEmail());
        entity.setPhone(form.getPhone());
        
        save(entity);
    }
}
